﻿namespace KinonekoSoftware.CodariaDB.Documents.Notions
{
    public sealed class NotionEngine : Engine
    {
        #region NotionDraft

        
        public bool        HasNotionDraft(string id) => NotionDB.HasID(id);
        public NotionDraft GetNotionDraft(string id) => NotionDB.FindById(id);
        
        public void Add(NotionDraft notion)
        {
            if (notion is null)
            {
                return;
            }

            NotionDB.Insert(notion);
            Modified();
        }
        
        public void Update(NotionDraft notion)
        {
            if (notion is null)
            {
                return;
            }

            NotionDB.Update(notion);
            Modified();
        }
        
        public void Clear(NotionDraft notion)
        {
            if (notion is null)
            {
                return;
            }

            NotionDB.Delete(notion.Id);
            Modified();
        }

        #endregion

        #region Mission

        
        public void Add(Mission notion)
        {
            if (notion is null)
            {
                return;
            }

            MissionDB.Insert(notion);
            Modified();
        }
        
        public void Update(Mission notion)
        {
            if (notion is null)
            {
                return;
            }

            MissionDB.Update(notion);
            Modified();
        }
        
        public void Clear(Mission notion)
        {
            if (notion is null)
            {
                return;
            }

            MissionDB.Delete(notion.Id);
            Modified();
        }

        public IEnumerable<Mission> GetMissions(ISet<string> missions)
        {
            return MissionDB.Find(x => missions.Contains(x.Id));
        }
        
        #endregion
        
        protected override void OnDatabaseOpening(RepositoryOpenContext context)
        {
            var repo = context.Repository;
            NotionDB  = repo.Get<NotionDraft>(CollectionNames.NotionDB);
            MissionDB = repo.Get<Mission>(CollectionNames.MissionDB);
        }

        protected override void OnDatabaseClosing(ILogger logger)
        {
            NotionDB      = null;
            MissionDB     = null;
            InspirationDB = null;
        }
        
        public bool HasNotion(string id) => InspirationDB.HasID(id);


        public ILiteCollection<NotionDraft> NotionDB { get; private set; }
        public ILiteCollection<Mission> MissionDB { get; private set; }
        public ILiteCollection<Inspiration> InspirationDB { get; private set; }
        
        public override string  EngineID => EngineNames.Notion;

    }
}